﻿using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using YaP.Library.XmlModels;

namespace YaP.Library
{
    internal class OptionsFactory
    {
        public readonly string OptionFilePath;

        #region Constructors

        public OptionsFactory()
        {
            OptionFilePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\options.xml";
        }

        public OptionsFactory(string FilePath)
        {
            OptionFilePath = FilePath;
        }

        #endregion

        #region Public Properies

        public CONFIG CurrentConfig
        {
            get
            {
                XmlSerializer xmls = new XmlSerializer(typeof (CONFIG));


                XmlReader reader = null;
                try
                {
                    reader = new XmlTextReader(new FileStream(OptionFilePath, FileMode.Open));
                    CONFIG root = (CONFIG) xmls.Deserialize(reader);
                    reader.Close();
                    return root;
                }
                catch (InvalidOperationException)
                {
                    //Typically, this exception is raised when there is a probleme with the option XML file format.
                    reader.Close();
                    CurrentConfig = HardenedConfig;
                    return HardenedConfig;
                }
                catch (FileNotFoundException)
                {
                    //the options has been deleted, YaP must have it. We're gonna create it with the hardened config.
                    CurrentConfig = HardenedConfig;
                    return HardenedConfig;
                }
            }
            set
            {
                XmlSerializer xmls = new XmlSerializer(typeof (CONFIG));
                XmlTextWriter writer = new XmlTextWriter(OptionFilePath, System.Text.Encoding.UTF8);
                CONFIG cfg = value;
                xmls.Serialize(writer, cfg);
                writer.Close();
            }
        }

        private CONFIG HardenedConfig
        {
            get
            {
                CONFIG hdcfg = new CONFIG();
                hdcfg.ALT = "YaP-Alt";
                hdcfg.EMAIL = "YapMail@yap.com";
                hdcfg.NICK = "YaP-Nick";
                hdcfg.PREVSERV = "irc.librenet.net";
                hdcfg.PREVPORT = "6667";
                return hdcfg;
            }
        }

        #endregion
    }
}